const jwt = require('jsonwebtoken')
const signKey = 'mes_qdhd_mobile';
const utils = {
    // 设定msg字段为错误提醒字段
    // numberArr 是类型转换数组，需要在mustArr或notMustArr数组中先申明
    checkParams(options = {}) {
        let params = {};
        const {
            data = {},
                mustArr = [],
                notMustArr = [],
                numberArr = [],
        } = options;
        mustArr.forEach((item, index) => {
            if (!data[item]) {
                params['msg'] = `参数错误:${item}`
            } else {
                params[item] = data[item]
            }
        });
        notMustArr.forEach((item, index) => {
            if (data[item]) {
                params[item] = data[item];
            }
        })
        numberArr.forEach((item, index) => {
            if (params[item]) {
                params[item] = Number(params[item])
            }
        })
        return params;
    },
    // 设置token
    setToken(username) {
        return new Promise((resolve, reject) => {
            const token = jwt.sign({
                username
            }, signKey, {
                expiresIn: 60 * 60 * 3 // 3小时过期
            })
            resolve(token)
        })
    },
    // 验证token
    verifyToken(token) {
        return new Promise((resolve, reject) => {
            jwt.verify(token, signKey, (error, decoded) => {
                if (error) {
                    reject(error)
                } else {
                    resolve(decoded)
                }
            })
        })
    },
    // 日期转化
    renderTime(date) {
        let date1 = new Date(date).toJSON();
        return new Date(+new Date(date1) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
    }

}

module.exports = utils;